package com.estronger.shopmanage.ui.install;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B12Measure;
import com.estronger.shopmanage.bean.B32BuildContent;
import com.estronger.shopmanage.bean.BeanImage;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.view.AddPhotosView;
import com.estronger.shopmanage.view.YesRecordView;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.soonfor.evaluate.tools.ImageUtils;
import com.estronger.shopmanage.utils.Toast;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 客户证言登记
 */
@SuppressWarnings("ResourceType")
public class TestimonyActivity extends BaseActivity implements AddPhotosView.EventListener {

	private Activity mActivity;
	private TextView tv_name;
	private LinearLayout tesimony_layout;
	private String dlvid;
	private View rootView;
	private RequestParams savaParams;
	private EditText et_test_remark;
	//上传录音
	private String uploadMP3path;//上传录音
	private YesRecordView view_yes_record;
	private int recordingLong = 0;//录音的时长
	//上传图片
	private AddPhotosView view_customer_testimony;
	private final int CODE_ADDPHOTO_TESIMONY = 7000;
	private boolean tesimonyPicUploadFn = false;
	private ArrayList<String> tesimonyPicPaths = new ArrayList<String>();//已上传的证言图片

	@Override
	protected void init() {
		mActivity = TestimonyActivity.this;
		dlvid = mActivity.getIntent().getStringExtra("dlvid");
		RequestParams params = new RequestParams();
		params.addBodyParameter("sf_action", "getistinfo");
		params.addBodyParameter("usercode", MyApplication.getUserCode());
		params.addBodyParameter("dlvid", dlvid);
		connect(params, NetManager.BUILD_DETAIL);
	}

	@Override
	protected void initView() {
		rootView = View.inflate(this, R.layout.activity_tesimony, null);
		setContentView(rootView);
		findViewByIds();
		initModule();
	}

	private void findViewByIds() {
		tv_name = (TextView) findViewById(R.id.finish_item_name_real);
		et_test_remark = (EditText) findViewById(R.id.test_input_remark);
		tesimony_layout = (LinearLayout) findViewById(R.id.tesimony_layout);
		// record_tip = (TextView) findViewById(R.id.record_tip);
		view_yes_record = (YesRecordView) findViewById(R.id.view_yes_record);
		view_customer_testimony =  findViewById(R.id.view_customer_testimony);
	}

	//初始化组件
	private void initModule() {
		view_yes_record.initView(mActivity, rootView, new YesRecordView.ActionListener() {
			@Override
			public void saveRecord(String recordPath) {
				File file = new File(recordPath);
				// if (file.exists())
				// Log.i("JSON", "local recordPath = " + recordPath);
				RequestParams p = new RequestParams();
				p.addBodyParameter("usercode", MyApplication.getUserCode());
				p.addBodyParameter("dir", "file");
				p.addBodyParameter("imgFile", file);
				connect(p, NetManager.FILEUPDATE);
				view_yes_record.afterSave(recordPath);
			}

			@Override
			public void updateUpTime(int upTime) {
				recordingLong = upTime;
			}
		});
		view_customer_testimony.initView(mActivity, CODE_ADDPHOTO_TESIMONY, this);
		view_customer_testimony.initData("客户证言卡拍照", 99);
	}

	@Override
	protected void onNetSuccess(int code, String result) {
		// Log.i("result", "DETAIL = " + result);
		if (NetManager.BUILD_DETAIL == code) {
			super.onNetSuccess(code, result);
			B32BuildContent detail = gson.fromJson(result,
					B32BuildContent.class);
			if (detail.success && detail.data != null) {

				if (TextUtils.isEmpty(detail.data.buildname)) {
					tv_name.setText(detail.data.cstname);
				} else {
					tv_name.setText(detail.data.buildname + "-"
							+ detail.data.cstname);
				}

			}
		}else if (NetManager.FILEUPDATE == code) {//上传录音文件
			BeanImage bean = gson.fromJson(result, BeanImage.class);
			if (bean.error == 0) {
				uploadMP3path = bean.filepath;
				// Log.i("JSON", "uploadMP3path = " + uploadMP3path);
				view_yes_record.clear();
			}
		}else if (NetManager.BUILD_FINISH == code) {//证言提交
			super.onNetSuccess(code, result);
			B12Measure designer = gson.fromJson(result, B12Measure.class);
			// 进入activity时获取的同事信息
			savaParams = null;
			if (designer.success) {
				Toast.show(mActivity, "证言信息提交成功", 2000);
				setResult(BuildActivity.REFLESH_DATA);
				finish();// designer.msg
			} else {
				Toast.show(mActivity, "证言信息提交失败 = " + designer.msg, 2000);
				Log.i("JSON", "提交失败 = " + designer.msg);
			}
			closeLoadDialog();
		}
	}

	@Override
	protected void onNetErorr(int code, String msg) {
		if (code == CODE_ADDPHOTO_TESIMONY) view_customer_testimony.uploadFail(CODE_ADDPHOTO_TESIMONY, msg);
		else  if (NetManager.BUILD_FINISH == code) {//证言信息提交
			super.onNetErorr(code, msg);
			savaParams = null;
			closeLoadDialog();
		}else if (NetManager.FILEUPDATE == code) {
			Log.i("JSON", "error uploadMP3path = " + uploadMP3path);
		}
	}

	public void testimony(View view) {

//		if (img_contener.getChildCount() == 0) {
//			Toast.show(this, "提交证言时必须同时提交相应的图片", 2000);
//			return;
//		}
        savaParams = new RequestParams();
        savaParams.addBodyParameter("sf_action", "postisttestimony");
        savaParams.addBodyParameter("usercode", MyApplication.getUserCode());
        savaParams.addBodyParameter("dlvid", dlvid);
        savaParams.addBodyParameter("testimonytxt", et_test_remark.getText().toString());
        //提交证言图片
		initUpload();
		view_customer_testimony.postPics();
	}
	private void initUpload() {
		showDialog("提交数据中...", false);
		if (tesimonyPicPaths == null) tesimonyPicPaths = new ArrayList<>();
		else tesimonyPicPaths.clear();
		tesimonyPicUploadFn = false;
	}

	public void switch_radio(View view) {
		CheckBox cb = (CheckBox) (((RelativeLayout) (view)).getChildAt(1));
		if (cb.isChecked()) {
			cb.setChecked(false);
			// valueAnim(getLongMeasureHeight(tesimony_layout), 0,
			// tesimony_layout);
			tesimony_layout.setVisibility(View.GONE);
		} else {
			cb.setChecked(true);
			// valueAnim(0, getLongMeasureHeight(tesimony_layout),
			// tesimony_layout);
			tesimony_layout.setVisibility(View.VISIBLE);
		}
	}

	public int getLongMeasureHeight(ViewGroup view) {
		int width = view.getMeasuredWidth();
		view.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;

		int widthMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY,
				width);
		int heightMeasureSpec = MeasureSpec.makeMeasureSpec(
				MeasureSpec.AT_MOST, 1000);
		view.measure(widthMeasureSpec, heightMeasureSpec);//
		return view.getMeasuredHeight();
	}


	@Override
	protected void onActivityResult(int request, int result, Intent data) {
		super.onActivityResult(request, result, data);
		if (result != Activity.RESULT_OK) return;
		view_customer_testimony.onActivityResult(request, data);
	}

	@Override
	protected void onDestroy() {
		view_yes_record.destory();
		super.onDestroy();
	}

	//打开图库
	@Override
	public void openAlbum(int id) {
		if (isOutOfLimit(id)) return;
		List<LocalMedia> lastMedias = new ArrayList<>();
		if (id == CODE_ADDPHOTO_TESIMONY) {
			lastMedias.addAll(view_customer_testimony.getFileList());
		}
		ImageUtils.pictureSelect(mActivity, PictureConfig.MULTIPLE, 99, lastMedias, id + 1);
	}

	//打开相机拍照
	@Override
	public boolean openCamera(int id) {
		// 当达到最高图片数量时直接返回
		return isOutOfLimit(id);
//		if (isOutOfLimit(id))
//			return;
//		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//		startActivityForResult(intent, id + 2);
	}

	/**
	 * 判断容器里的图片是否达到最高选择数量
	 */
	private boolean isOutOfLimit(int code) {
		// 下面开始判断整体容器里的图片是否达到最高选择数量
		if (code == CODE_ADDPHOTO_TESIMONY) {
			if (view_customer_testimony.getPhotosCount() >= 99) {
				Toast.show(mActivity, "客户证言图片最多可上传99张", 2000);
				return true;
			}
		}
		return false;
	}

	@Override
	public void showLoadDialog() {
	}

	@Override
	public void closeLoadDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
	}

	//上传单张图片
	@Override
	public void uploadPic(RequestParams params, int requstoCode) {
		updateIMG(params, requstoCode);
	}

	@Override
	public void uploadVideoByParam(RequestParams params, int code) {
		uploadVideo(params, code);
	}

	@Override
	public void afterUploadVideos(boolean isSuccess, ArrayList<BeanImage> urls, int requestCode) {

	}

	//所有图片上传成功
	@Override
	public void afterUploadPics(boolean isSuccess, ArrayList<String> urls, int code) {
		if (isSuccess) {
			if (code == CODE_ADDPHOTO_TESIMONY) {
				tesimonyPicUploadFn = true;
				tesimonyPicPaths = urls;
			}
			buildJson();
		}else {
			closeLoadDialog();
		}
	}
	// 组建json提交服务器
	private void buildJson() {
		if (tesimonyPicUploadFn) {
			buildIMGJson();
		}
	}
	// 组建json提交服务器
	private void buildIMGJson() {
		try {
			JSONArray jsonArr = new JSONArray();
			for (int i = 0; i <tesimonyPicPaths.size(); i++) {
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("dlvid", dlvid);
				jsonObj.put("imgpath", tesimonyPicPaths.get(i));
				jsonObj.put("filetype", "1");
				jsonObj.put("filelength", recordingLong);
				jsonArr.put(jsonObj);
			}

			if (!TextUtils.isEmpty(uploadMP3path)) {
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("dlvid", dlvid);
				jsonObj.put("imgpath", uploadMP3path);
				jsonObj.put("filetype", "2");
				jsonObj.put("filelength", recordingLong);
				jsonArr.put(jsonObj);
			}
			savaParams.addBodyParameter("voiceitem", jsonArr.toString());
			Log.i("GAOUJ", "BUILD JSON = " + jsonArr.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		connect(savaParams, NetManager.BUILD_FINISH);
	}

	/**
	 * 上传图片成功的回调
	 * @param code
	 * @param result
	 */
	@Override
	protected void onNetIMGSuccess(int code, String result) {
		if (code == CODE_ADDPHOTO_TESIMONY) view_customer_testimony.uploadSuccess(code,result);
	}

}
